package com.taoye.thread;

public class Demo35 {
	public static void main(String[] args) throws InterruptedException {
		Demo35Service service = new Demo35Service();
		service.setFlg(true);
		Thread t = new Demo35ThreadA(service);
		t.start();
		//预计在3秒后停止线程
		Thread.sleep(3000);
		service.setFlg(false);
	}
}

class Demo35Service {

	private boolean flg;

	public boolean isFlg() {
		return flg;
	}

	public void setFlg(boolean flg) {
		System.out.println(Thread.currentThread().getName()+"线程设置了flg："+flg);
		this.flg = flg;
	}

	/**
	 * 模拟业务方法
	 */
	public void fun() {
		
	}
}

class Demo35ThreadA extends Thread {
	private Demo35Service service;
	//修改为下列方式，即可正确停止线程
//	private volatile Demo35Service service;

	public Demo35ThreadA(Demo35Service service) {
		this.service = service;
	}

	@Override
	public void run() {
		while (service.isFlg()) {
			//这里假装调用某个业务方法
			service.fun();
		}
	}
}
